package com.cropdoctor.controller;

import com.cropdoctor.common.Result;
import com.cropdoctor.mapper.PrePublishCourseMapper;
import com.cropdoctor.model.constants.PageParams;
import com.cropdoctor.model.constants.PageResult;
import com.cropdoctor.model.dto.*;
import com.cropdoctor.model.po.*;
import com.cropdoctor.model.vo.FeedBackVO;
import com.cropdoctor.model.vo.PostVO;
import com.cropdoctor.model.vo.UserVO;
import com.cropdoctor.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin")
@Api(tags = "管理员端相关接口")
public class AdminController {
    @Autowired
    AdminService adminService;
    @Autowired
    VegeFruTableService vegeFruTableService;

    @Autowired
    PrePublishCourseMapper prePublishCourseMapper;

    @Autowired
    CourseService courseService;

    @Autowired
    FeedBackService feedBackService;

    @Autowired
    PostService postService;

    @Autowired
    CommentService commentService;
    @Autowired
    RegisterService registerService;

    @Autowired
    VideoSummaryService videoSummaryService;

    // ==================== 路径权限配置模块 ====================
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysPermissionService sysPermissionService;
    @Autowired
    private SysRequestPathService sysRequestPathService;
    @Autowired
    private SysRolePermissionService sysRolePermissionService;
    @Autowired
    private SysRequestPathPermissionService sysRequestPathPermissionService;
    // 你需要实现/注入如下Service
    // @Autowired
    // private SysRequestPathService sysRequestPathService;
    // @Autowired
    // private SysRolePermissionService sysRolePermissionService;
    // @Autowired
    // private SysRequestPathPermissionService sysRequestPathPermissionService;

    //#region 管理员端(果蔬表数据管理)
    @DeleteMapping("/category")
    public Result<String> DelCategories(Long id) {
        return vegeFruTableService.delCategories(id);
    }

    @PutMapping("/category")
    public Result<String> EditCategories(@RequestBody CategoryPo categoryPo) {
        return vegeFruTableService.editCategories(categoryPo);
    }

    @PostMapping("/category")
    public Result<String> addCategories(@RequestBody CategoryPo categoryPo) {
        return vegeFruTableService.addCategories(categoryPo);
    }

    @PostMapping("/table")
    public Result<String> addVegeFru(@RequestParam("url") MultipartFile img,AddOrUpdateVegeFrutableDto addOrUpdateVegeFrutableDto){
        addOrUpdateVegeFrutableDto.setImg(img);
        return vegeFruTableService.addOrUpdateVegeFru(addOrUpdateVegeFrutableDto);
    }

    @PutMapping("/table")
    public Result<String> updateVegeFru(@RequestParam(value = "url",required = false) MultipartFile img,AddOrUpdateVegeFrutableDto addOrUpdateVegeFrutableDto){
        addOrUpdateVegeFrutableDto.setImg(img);
        return vegeFruTableService.addOrUpdateVegeFru(addOrUpdateVegeFrutableDto);
    }

    @DeleteMapping("/table")
    public Result<String> delVegeFru(@RequestParam long id){
        return vegeFruTableService.delVegeFru(id);
    }
    //#endregion

    //#region 视频审核部分
    @ApiOperation("管理员获取所有待发布课程相关信息")
    @GetMapping("/course")
    public Result<List<PrePublishCoursePo>> getCourse(){
        return courseService.getAllPrePublishCourse();//获得待发布课程信息
    }

    @PatchMapping("/course/audit/{id}/{status}")
    @ApiOperation("管理员审核课程")
    public Result<String> auditCourse(@PathVariable String id,@PathVariable String status,@RequestBody(required = false) String auditMind){
        return courseService.auditCourse(status,auditMind,id);//审核待发布课程信息
    }

    @ApiOperation("管理员获取单条待发布课程详细信息")
    @GetMapping("/course/{courseId}")
    public Result<PrePublishCourseDto> getCourseInfo(@PathVariable Long courseId){
        return courseService.getPrePublishCourseInfo(courseId);
    }

    @GetMapping("/course/history")
    @ApiOperation("管理员获取审核历史记录")
    public Result<List<AuditHistoryDto>> getAuditHistory(@RequestParam(required = false) LocalDate endDate, @RequestParam(required = false) LocalDate beginDate){
        return courseService.getAuditHistory(endDate,beginDate);//审核待发布课程信息
    }
    //#endregion

    //#region AI视频总结功能
    @PostMapping("/course/ai-summary")
    @ApiOperation("生成视频AI总结")
    public Result<String> generateVideoSummary(@RequestBody VideoSummaryRequestDto request) {
        try {
            String summary = videoSummaryService.generateSummary(request);
            return Result.success(summary);
        } catch (Exception e) {
            return Result.error("生成总结失败: " + e.getMessage());
        }
    }

    @PostMapping("/course/save-summary")
    @ApiOperation("保存视频总结")
    public Result<VideoSummaryDto> saveVideoSummary(@RequestBody Map<String, Object> requestData) {
        try {
            Long courseId = Long.valueOf(requestData.get("courseId").toString());
            String summary = requestData.get("summary").toString();
            String provider = requestData.get("provider").toString();

            VideoSummaryDto result = videoSummaryService.saveSummary(courseId, summary, provider);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("保存总结失败: " + e.getMessage());
        }
    }

    @GetMapping("/course/summary/{courseId}")
    @ApiOperation("获取视频总结")
    public Result<VideoSummaryDto> getVideoSummary(@PathVariable Long courseId) {
        try {
            VideoSummaryDto result = videoSummaryService.getLatestSummaryByCourseId(courseId);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取总结失败: " + e.getMessage());
        }
    }
    //#endregion

    //region 管理员端(帖子管理)
    @DeleteMapping("/post/{idPost}")
    @ApiOperation(value = "管理员通过帖子的主键id删除相应的帖子")
    public Result<String> adminDeletePost(@PathVariable("idPost") long idPost){
        return postService.adminDeletePost(idPost);
    }

    @GetMapping("/post")
    @ApiOperation(value = "管理员获取当前论坛中的所有帖子")
    public Result<PageResult<PostVO>> getAllPost(PageParams pageParams, @RequestParam(required = false,defaultValue = "")String keyword){
        return postService.getAllPost(pageParams,keyword);
    }

    //endregion

    //region 管理员端(评论管理)
    @GetMapping("/post/comment/{idPost}")
    @ApiOperation(value = "获取当前帖子中的所有评论")
    public Result<PostDto> getAllComment(@PathVariable("idPost") long idPost){
        return commentService.getPostWithAllComment(idPost);
    }

    @GetMapping("/comment/{idComment}")
    @ApiOperation(value = "根据评论的主键id，获取单条评论信息")
    public Result<CommentPo> getComment(@PathVariable("idComment") long idComment){
        return commentService.getComment(idComment);
    }

    @DeleteMapping("/comment/{idComment}")
    @ApiOperation(value = "根据传入的评论表主键id，删除用户的评论")
    public Result<String> adminDeleteComment(@PathVariable("idComment") long idComment){
        return commentService.adminDeleteComment(idComment);
    }
    //endregion

    //region反馈模块（管理员端）
    @GetMapping("/feedback")
    @ApiOperation("（管理员端）在管理员端查询所有反馈信息")
    public Result<List<FeedBackVO>> getAllFeedBack(){
        return feedBackService.adminGetAllFeedBack();
    }

    @DeleteMapping("/feedback/{id}")
    @ApiOperation("（管理员端）处理完反馈后，通过传入的主键id，删除对应的反馈信息")
    public Result<String> adminDeleteById(@PathVariable("id") Long id){
        return feedBackService.adminDeleteById(id);
    }
    //endregion

    //region 管理员端(账号管理)
    @PostMapping("/register")
    @ApiOperation("用户注册账号")
    public Result<String> userRegister(@RequestBody SysUserPo sysUserPo ,@RequestParam MultipartFile img){
        return registerService.userRegister(sysUserPo,img);
    }

    @PostMapping("/account")
    @ApiOperation("由管理员用户新增一名管理员用户")
    public Result<String> addAdmin(@RequestBody SysUserPo sysUserPo , @RequestParam MultipartFile img){
        return adminService.addAdmin(sysUserPo,img);
    }

    @PatchMapping("/account/role/{idUser}/{roleId}")
    @ApiOperation("由管理员用户新增一名管理员用户")
    public Result<String> changeRole(@PathVariable("idUser") Long userId,@PathVariable("roleId") int roleId){
        return adminService.changeRole(userId,roleId);
    }

    @PatchMapping("/account/status/{idUser}/{status}")
    @ApiOperation("由管理员将id对应的账户设置为启用状态")
    public Result<String> enableUser(@PathVariable("idUser") Integer idUser,@PathVariable("status") String status){
        return adminService.changeUserStatus(idUser,status);
    }

    @PatchMapping("/account/reset/{idUser}")
    @ApiOperation("管理员重置用户的密码，默认为(123)")
    public Result<String> resetPassword(@PathVariable("idUser") Integer idUser){
        return adminService.resetPassword(idUser);
    }

    @GetMapping("/account")
    @ApiOperation("管理员获取所有用户列表")
    public Result<PageResult<UserVO>> getAllUser(@RequestParam int pageNo,
                                                 @RequestParam int pageSize,
                                                 @RequestParam(required = false,defaultValue = "") String account){
        PageParams pageParams = new PageParams(pageNo, pageSize);
        return adminService.getAllUser(pageParams,account);
    }

    @GetMapping("/account/{idUser}")
    @ApiOperation("根据传入的idUser，查询对应的用户信息")
    public Result<SysUserPo> getUser(@PathVariable("idUser") Integer idUser){
        return adminService.getUser(idUser);
    }
    //endregion

    /**
     * 1.1 获取所有角色
     */
    @GetMapping("/role")
    @ApiOperation("获取所有角色")
    public Result<List<SysRolePo>> getAllRoles() {
        List<SysRolePo> roles = sysRoleService.list();
        return Result.success(roles);
    }

    /**
     * 获取所有权限，支持?type=ids返回所有权限ID
     */
    @GetMapping("/permission")
    @ApiOperation("获取所有权限")
    public Result<?> getAllPermissions(@RequestParam(value = "type", required = false) String type) {
        List<SysPermissionPo> permissions = sysPermissionService.list();
        if ("ids".equalsIgnoreCase(type)) {
            List<Integer> ids = permissions.stream()
                .map(p -> {
                    try {
                        java.lang.reflect.Field idField = p.getClass().getDeclaredField("id");
                        idField.setAccessible(true);
                        return (Integer) idField.get(p);
                    } catch (Exception e) {
                        return null;
                    }
                })
                .filter(java.util.Objects::nonNull)
                .collect(java.util.stream.Collectors.toList());
            return Result.success(ids);
        }
        return Result.success(permissions);
    }

    /**
     * 获取所有路径，支持?type=ids返回所有路径ID
     */
    @GetMapping("/path")
    @ApiOperation("获取所有路径")
    public Result<?> getAllPaths(@RequestParam(value = "type", required = false) String type) {
        List<SysRequestPathPo> paths = sysRequestPathService.list();
        if ("ids".equalsIgnoreCase(type)) {
            List<Long> ids = paths.stream()
                .map(p -> {
                    try {
                        java.lang.reflect.Field idField = p.getClass().getDeclaredField("id");
                        idField.setAccessible(true);
                        return (Long) idField.get(p);
                    } catch (Exception e) {
                        return null;
                    }
                })
                .filter(java.util.Objects::nonNull)
                .collect(java.util.stream.Collectors.toList());
            return Result.success(ids);
        }
        return Result.success(paths);
    }

    /**
     * 4.1 获取某角色拥有的权限
     * 支持 ?type=ids 返回id数组，默认返回对象数组
     */
    @GetMapping("/role/{roleId}/permissions")
    @ApiOperation("获取某角色拥有的权限")
    public Result<?> getPermissionsByRole(@PathVariable Integer roleId, @RequestParam(value = "type", required = false) String type) {
        if ("ids".equalsIgnoreCase(type)) {
            List<Integer> ids = sysRolePermissionService.getPermissionIdsByRoleId(roleId);
            return Result.success(ids);
        }
        List<SysPermissionPo> permissions = sysRolePermissionService.getPermissionsByRoleId(roleId);
        return Result.success(permissions);
    }

    /**
     * 4.2 设置某角色拥有的权限
     */
    @PostMapping("/role/{roleId}/permissions")
    @ApiOperation("设置某角色拥有的权限")
    public Result<String> setPermissionsByRole(@PathVariable Integer roleId, @RequestBody IdsDTO dto) {
        sysRolePermissionService.setPermissionsForRole(roleId, dto.getPermissionIds());
        return Result.success("设置成功");
    }

    /**
     * 5.1 获取某权限拥有的路径
     */
    @GetMapping("/permission/{permissionId}/paths")
    @ApiOperation("获取某权限拥有的路径")
    public Result<List<SysRequestPathPo>> getPathsByPermission(@PathVariable Integer permissionId) {
        List<SysRequestPathPo> paths = sysRequestPathPermissionService.getPathsByPermissionId(permissionId);
        return Result.success(paths);
    }

    /**
     * 5.2 设置某权限拥有的路径
     */
    @PostMapping("/permission/{permissionId}/paths")
    @ApiOperation("设置某权限拥有的路径")
    public Result<String> setPathsByPermission(@PathVariable Integer permissionId, @RequestBody IdsDTO dto) {
        sysRequestPathPermissionService.setPathsForPermission(permissionId, dto.getPathIds());
        return Result.success("设置成功");
    }

    @PostMapping("/path")
    @ApiOperation("新增路径")
    public Result<String> addPath(@RequestBody SysRequestPathPo pathPo) {
        if (pathPo.getUrl() == null || pathPo.getUrl().trim().isEmpty()) {
            return Result.error("路径URL不能为空");
        }
        sysRequestPathService.save(pathPo);
        return Result.success("新路径已添加");
    }

    @PutMapping("/path/{id}")
    @ApiOperation("修改路径")
    public Result<String> updatePath(@PathVariable Integer id, @RequestBody SysRequestPathPo pathPo) {
        if (pathPo.getUrl() == null || pathPo.getUrl().trim().isEmpty()) {
            return Result.error("路径URL不能为空");
        }
        pathPo.setId(id);
        sysRequestPathService.updateById(pathPo);
        return Result.success("路径已修改");
    }

    @DeleteMapping("/path/{id}")
    @ApiOperation("删除路径")
    public Result<String> deletePath(@PathVariable Integer id) {
        sysRequestPathService.removeById(id);
        return Result.success("路径已删除");
    }

    @PostMapping("/permission")
    @ApiOperation("新增权限")
    public Result<String> addPermission(@RequestBody SysPermissionPo po) {
        if (po.getPermissionName() == null || po.getPermissionName().trim().isEmpty()) {
            return Result.error("权限名不能为空");
        }
        sysPermissionService.save(po);
        return Result.success("新权限已添加");
    }

    @PutMapping("/permission/{id}")
    @ApiOperation("修改权限")
    public Result<String> updatePermission(@PathVariable Integer id, @RequestBody SysPermissionPo po) {
        if (po.getPermissionName() == null || po.getPermissionName().trim().isEmpty()) {
            return Result.error("权限名不能为空");
        }
        po.setId(id);
        sysPermissionService.updateById(po);
        return Result.success("权限已修改");
    }

    @DeleteMapping("/permission/{id}")
    @ApiOperation("删除权限")
    public Result<String> deletePermission(@PathVariable Integer id) {
        sysPermissionService.removeById(id);
        return Result.success("权限已删除");
    }
}
